package com.shuangyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuangyu.common.BaseContext;
import com.shuangyu.common.R;
import com.shuangyu.entity.Orders;
import com.shuangyu.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     * @param order
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders order){

        orderService.submit(order);

        return R.success("操作成功");
    }

    @GetMapping("/userPage")
    public R<Page<Orders>> userPage(int page, int pageSize){

        long userId = BaseContext.getCurrentId();

        Page<Orders> pageInfo = new Page<Orders>(page, pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId);

        orderService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    @GetMapping("/page")
    public R<Page<Orders>> Page(int page, int pageSize, Long number, String beginTime, String endTime){

        Page<Orders> pageInfo = new Page<Orders>(page, pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(number != null, Orders::getNumber, number);

        orderService.page(pageInfo, queryWrapper);

        List<Orders> records = pageInfo.getRecords();

        if (beginTime != null && endTime != null){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime beginDateTime = LocalDateTime.parse(beginTime, df);
            LocalDateTime endDateTime = LocalDateTime.parse(endTime, df);

            List<Orders> list = new ArrayList<>();

            for (Orders order : records) {
                if (order.getOrderTime().isAfter(beginDateTime) && order.getOrderTime().isBefore(endDateTime)) {
                    list.add(order);
                }
            }

            Page<Orders> ordersPage = new Page<>();
            ordersPage.setTotal(list.size());
            ordersPage.setRecords(list);

            return R.success(ordersPage);
        }

        return R.success(pageInfo);
    }

}
